/*
 * Copyright(c) 2020-2100 万达信息股份有限公司 版权所有
 * WONDERS INFORMATION CO., LTD. ALL RIGHTS RESERVED.
 */

package com.wondersgroup;

/**
 * 完美解决方案
 * 双重检查 + synchronized
 * @author: huym
 * @version: 1.0
 * @date: 2020/12/9
 */
public class Mgr06 {

    //加volatile可防止JIT编译成本地语言时，指令重排
    private static volatile Mgr06 INSTANCE;

    private Mgr06(){}

    public static Mgr06 getInstance(){
        if (INSTANCE==null) {
            // 双重检查
            synchronized (Mgr06.class) {
                if (INSTANCE==null) {
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    INSTANCE = new Mgr06();
                }
            }
        }
        return INSTANCE;
    }

    public void m(){
        System.out.println("m");
    }

    public static void main(String[] args) {
        for (int i=0;i<100;i++){
            new Thread(()->System.out.println(Mgr06.getInstance().hashCode())).start();
        }
    }

}